//
// Description: 15. 三数之和
// Created by Loading on 2022/3/13.
//

#include <bits/stdc++.h>

using namespace std;

vector<vector<int>> threeSum(vector<int> &nums) {
    int n = nums.size();
    vector<vector<int>> res;
    sort(nums.begin(), nums.end());
    for (int i = 0; i < n; ++i) {
        // 跳过重复元素
        if (i > 0 && nums[i] == nums[i - 1]) {
            continue;
        }
        // 双指针
        int j = i + 1;
        int k = n - 1;
        while (j < k) {
            if (nums[i] + nums[j] + nums[k] == 0) {
                res.push_back({nums[i], nums[j], nums[k]});
                ++j;
                --k;
                // 跳过重复元素
                while (j < k && nums[j] == nums[j - 1]) {
                    ++j;
                }
                while (j < k && nums[k] == nums[k + 1]) {
                    --k;
                }
            } else if (nums[i] + nums[j] + nums[k] < 0) {
                ++j;
            } else {
                --k;
            }
        }
    }

    return res;
}

int main() {
    vector<int> nums{0, 0, 0, 0};
    auto res = threeSum(nums);
    for (auto v : res) {
        cout << v[0] << ' ' << v[1] << ' ' << v[2] << endl;
    }

    return 0;
}